layui
  .extend({
    conf: 'config',
    api: 'lay/modules/api',
    view: 'lay/modules/view'
  })
  .define(['conf', 'view', 'api', 'jquery'], function(exports) {
    POPUP_DATA = {}
    var conf = layui.conf
    var view = layui.view
    var element = layui.element
    var $ = layui.jquery
	
    layui.extend(conf.extend)
    var self = {}
    var windowWidth = $(window).width()
    self.route = layui.router()
    self.api = layui.api
    self.closeOnceHashChange = false
    self.ie8 = view.ie8
    self.get = view.request
    self.appBody = null
    self.shrinkCls = 'nepadmin-sidebar-shrink'
    self.isInit = false
    self.routeLeaveFunc = null
    self.loginToken = null
    self.routeLeave = function(callback) {
      this.routeLeaveFunc = callback
    }
    self.render = function(elem) {
      if (typeof elem == 'string') elem = $('#' + elem)
      var action = elem.get(0).tagName == 'SCRIPT' ? 'next' : 'find'
      elem[action]('[is-template]').remove()
      view.parse(elem)
    }
    self.getLoginToken = function() {
      if (self.loginToken == null) {
        self.loginToken =
          self.data()[conf.tokenName] ||
          layui.sessionData(conf.tableName, conf.tokenName)
      }
      return self.loginToken
    }
	self.navigate = function(url) {
	  if (url == conf.entry) url = '/'
	  window.location.hash = url
	}
	self.data = function(settings, storage) {
	  if (settings == undefined) return layui.data(conf.tableName)
	  if ($.isArray(settings)) {
	    layui.each(settings, function(i) {
	      layui.data(conf.tableName, settings[i], storage)
	    })
	  } else {
	    layui.data(conf.tableName, settings, storage)
	  }
	}
    self.logout = function() {
		self.data({ key: conf.tokenName, remove: true })
		self.data({ key: conf.tokenName, remove: true }, sessionStorage)
		self.data({ key: 'user', remove: true })
		self.data({ key: 'user', remove: true }, sessionStorage)
		self.data({ key: 'time', remove: true })
		self.loginToken = null
		self.navigate(conf.loginPage)
    }
	
	//表单自定义验证
	self.verify={
	    username: function(value, item){ //value：表单的值、item：表单的DOM对象
	      if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
	        return '用户名不能有特殊字符';
	      }
	      if(/(^\_)|(\__)|(\_+$)/.test(value)){
	        return '用户名首尾不能出现下划线\'_\'';
	      }
	      if(/^\d+\d+\d$/.test(value)){
	        return '用户名不能全为数字';
	      }
	    }
	    ,pass: [
	      /^[\S]{6,12}$/
	      ,'密码必须6到12位，且不能出现空格'
	    ] 
	  }
	  //表单验证
	  self.form=function(obj){
		  var obj=$(obj).find('.verify input,.verify textarea'),flag=true;
	      obj.each(function(index){
			  function hint(obj,msg){
				  if(msg){
					  obj.siblings('.hint').html(msg).parent().addClass('error');
				  }else{
					  obj.parents('.layui-input-block').addClass('error');
				  }
				  flag=false;
			  }
			  var verify=obj.eq(index).attr('verify'),val=$(this).val();
			  if(verify){
				  if(verify.indexOf('require')!=-1){
					  if(!(val.replace(/\s+/g,""))){
						  hint($(this));
					  }else if((val.replace(/\s+/g,"")).length>20&&verify.indexOf('requirel2')!=-1){
						  hint($(this),'字符长度不能超过20');
					  }else if((val.replace(/\s+/g,"")).length>50&&verify.indexOf('requirel5')!=-1){
						  hint($(this),'字符长度不能超过50');
					  }
				  }
				  if((verify.indexOf('username')!=-1)&&val){
					  if(val){
						  if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(val)){
							  hint($(this),'用户名不能有特殊字符');
						  }else if((/^\d+\d+\d$/).test(val)){
							  hint($(this),'用户名不能全为数字');
						  }else if((/(^\_)|(\__)|(\_+$)/).test(val)){
							  hint($(this),'用户名首尾不能出现下划线\'_\'');
						  }else if(!(/^[\S]{4,20}$/).test(val)){
							  hint($(this),'用户必须6到20位，且不能出现空格');
						  }
					  }
				  }
				  if((verify.indexOf('phone')!=-1)&&val){
				      if(!(/^1[3456789]\d{9}$/).test(val)){
				          hint($(this),'请输入合法的手机号');
				      }
				  }
				  if((verify.indexOf('pass')!=-1)&&val){
				      if(!(/^[\S]{6,20}$/).test(val)){
				          hint($(this),'密码必须6到20位，且不能出现空格');
				      }
				  }
				  if((verify.indexOf('realname')!=-1)&&val){
				      if(!(/^[\u4e00-\u9fa5]{2,4}$/).test(val)){
				          hint($(this),'真实姓名填写有误');
				      }
				  }
				  if((verify.indexOf('email')!=-1)&&val){
				      if(!(/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/).test(val)){
				          hint($(this),'邮箱填写有误');
				      }
				  }
				  if((verify.indexOf('card')!=-1)&&val){
				      if(!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(val)){
				          hint($(this),'身份证号填写有误');
				      }
				  }
				  if((verify.indexOf('znum')!=-1)&&val){
					  if((verify.indexOf('znum1')!=-1)&&val<1){
						  hint($(this),'不能小于1');
					  }
				      if(val<0){
				          hint($(this),'不能为负数');
				      }
				  }
				  if((verify.indexOf('range')!=-1)&&val){
					  if((verify.indexOf('znum1')!=-1)&&val<0){
						  hint($(this),'不能为负数');
					  }
					  if(val>=100){
						  hint($(this),'不能为大于等于100');
					  }
				  }
			  }
	      });
		  return flag;
	  }
	  $(document).on('focus','.verify input,.verify textarea',function(){
		  $(this).parents('.layui-input-block').removeClass('error');
	  })
	  //生成签名
	  self.sign=function(data){
		  if(data){
			 if(data.sign)delete data.sign;
			 for(var key in data){
			  if(!data[key]&&data[key]!==0){
				 data[key]='';
				 // delete data[key];
			  }
			 } 
		  }
		  var key={
			  time:Date.parse(new Date()).toString(),
			  rand_str:self.generateMixed(6),
			  appid:'123654258'
		  };
		  data ? Object.assign(data,key) :data=key;
		  self.data().user?data.token=self.data().user.token:'';
		  self.data().user?data.user_id=self.data().user.ad_id:'';
		  var nobj=self.objKeySort(data),sign='';
		  for(var key in nobj){
		  	sign+=nobj[key];
		  }
		  data.sign=sha1(layui.md5(sign)+'asdsgfdgfdgdfhfghgfhfghgfhdfcvbdfghfdgdf');
		  return data;
	  }
	  //接口请求
	self.ajax=function(url,data,h){
		return new Promise(function(resolve, reject){
			data=self.sign(data);
			var load=layer.load(1);
			$.ajax({
				url:conf.ajaxUrl+url,//'https://oldms.nkshuju.com/api/xydjinfo?type=page'
				type:'post',
				dataType:'json',
				data:data,
				success:function(res){

					layer.close(load);
					if(res.code==1){
						if(!h){
							self.ahint(1,res.msg);
						}
						resolve(res)
					}else{
						self.ahint(2,res.msg);
						if(res.code==3||res.code==5){
							setTimeout(function(){
								self.logout();
							},1000);
						}/* else if(res.code==4){
							view.tab.del(layui.router().href);
							self.navigate('/exception/403');
						} */
					}
				},
				error:function(res){
					layer.close(load);
					self.ahint(2,'数据请求异常');
					reject(res)
				}
			})
		})
	},
	//表格初始化
	self.initlist=function(table,url,height,cols,elem,fix_height,radio,datas,check,page=true,page_size=20,toolbar=false,totalRow=false){
		var wheres={};
		if(fix_height==509){
			wheres={member_id:layui.admin.objData.detail.member_id}
		}else if(datas){
			wheres=datas;
		}
		var ins1=table.render({
			elem: elem?elem:'#list-table',
			url: layui.conf.ajaxUrl+url,
			where:wheres
			,toolbar: toolbar
			,defaultToolbar: ['filter']
				,	request: {
			    pageName: 'page' 
			    ,limitName: 'page_size' 
			}
			,parseData: function(res){
				if(res.code==3){
					setTimeout(function(){
						self.logout();
					},1000);
				}/* else if(res.code==4){
					view.tab.del(layui.router().href);
					self.navigate('/exception/403');
				} */
				if(radio){
					for(var i=0; i<res.data.list.length; i++){
						if(res.data.list[i][radio.val1]==radio.obj[radio.val2]){
							res.data.list[i].LAY_CHECKED=true;
						}
					}
				}
				if(check){
					var list=[];
					if(check.obj){
						if(JSON.stringify(check.obj).indexOf(',')==-1){
							list.push(check.obj);
						}else{
							list=check.obj.split(',');
						}
					}

					for(var i=0; i<res.data.list.length; i++){
						for(var j=0; j<list.length; j++){
							if(res.data.list[i][check.val]==list[j]){
								res.data.list[i].LAY_CHECKED=true;
							}
						}
					}
				}
				return {
				  "code": res.code==1?0:1,
				  "msg": res.msg,
				  "count": res.data.count, 
				  "data": res.data.list
				};
			},



			limit: 20,

			limit: page_size,

			height: fix_height?fix_height:'full-'+height,
			cellMinWidth: 80,
			page: page,
			cols:cols,
			totalRow,totalRow

		});

	},
	//表格模拟数据初始化
	self.initlists=function(table,url,height,cols,totalRow=false){
		table.render({
			elem: '#list-table',
			url: url,
			height: 'full-'+height,
			cellMinWidth: 80,
			page: true,
			cols:cols,
			totalRow:totalRow

		});


	}
	  self.excel=function(table,url,datas,fix_height,elem) {

		  // if (fix_height == 509) {
			//   wheres = {member_id: layui.admin.objData.detail.member_id}
		  // } else if (datas) {
			//   wheres = datas;
		  // }
		  datas.is_excel=1;
		  datas=self.sign(datas);
		  var load=layer.load(1);
		  $.ajax({
			  url:conf.ajaxUrl+url,//'https://oldms.nkshuju.com/api/xydjinfo?type=page'
			  type:'post',
			  dataType:'json',
			  data:datas,
			  success:function(res){
				  layer.close(load);
				  if(res.code==1){
					  table.exportFile(elem?elem:'list-table',res.data.list);
				  }else{
				  }
			  },
			  error:function(res){
				  layer.close(load);
				  self.ahint(2,'数据请求异常');
				  reject(res)
			  }
		  })
	  };
	//搜索加载数据
	self.reloads=function(data,elem){
		layui.table.reload(elem?elem:'list-table', {
			page: {
				curr: 1
			},
			where: self.sign(data)
		});
	},
	//form提交请求
	self.formapi=function(url,data,is_reload=1){
		layui.admin.ajax(url,data).then(function(res){
			if (is_reload==1){
				layui.table.reload('list-table');
			}
			layer.close(self.pupFv);
		}).catch(function(res){});
	},
	//去重
	self.unique=function(arr){            
	        for(var i=0; i<arr.length; i++){
	            for(var j=i+1; j<arr.length; j++){
	                if(arr[i]==arr[j]){         //第一个等同于第二个，splice方法删除第二个
	                    arr.splice(j,1);
	                    j--;
	                }
	            }
	        }
	return arr;
	},
	//是否修改过滤
	self.filter=function(New,Old,Id){
		var data={};
		for(var i in New){
			if((JSON.stringify(New[i])!=JSON.stringify(Old[i]))||i==Id){
				data[i]=New[i];
			}
		}
		var l=Object.keys(data).length;
		if((Id&&l<2)||(!Id&&l<1)){
			layer.close(self.pupFv);
		}else{
			return data;
		}
	},
	//单个删除请求
	self.delF=function(table,url,data) {
		layui.admin.ajax(url,data).then(function(res){
			table.reload('list-table');
		}).catch(function(res){});
	},
	//多个删除请求
	self.delsF=function(table,url,id){
		var checkStatus = table.checkStatus('list-table')
		,checkData = checkStatus.data,dels,data={}; //得到选中的数据
		if(checkData.length === 0){
		  return layer.msg('请选择数据');
		}
		for(var i=0; i<checkData.length; i++){
			if(dels){
				dels+=','+checkData[i][id];
			}else{
				dels=checkData[i][id];
			}
		}
		data[id]=dels;
		
		layer.confirm('确定删除已选择的数据吗？', function(index) {
			self.delF(table,url,data);
		});
	},
	//提示信息
	self.ahint=function(code,msg){
		if(code==1){
			layer.msg(msg, {icon: 1});
		}else{
			layer.msg(msg, {icon: 2});
		}
	},
	//加载弹框内容
	self.pupF=function(title,area,url,type,detail){
		self.pupFv=layer.open({
			type:1,
		   id:'pup-cont',
		   title: title,
		   btn:[],
		   area: area,
		   success: function(layero, index){
			$('#pup-cont').load(conf.views+url+conf.engine);
			self.objData={type:type,detail:detail};
		   }
		})
	}
	//生成随机字符串
	var chars = ['0','1','2','3','4','5','6','7','8','9','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
	self.generateMixed=function(n){
	     var res = "";
	     for(var i = 0; i < n ; i ++) {
	         var id = Math.ceil(Math.random()*35);
	         res += chars[id];
	     }
	     return res;
	
	}
	self.objKeySort=function(obj) {
	    var newkey = Object.keys(obj).sort();
	    var newObj = {};
	    for (var i = 0; i < newkey.length; i++) {
	        newObj[newkey[i]] = obj[newkey[i]];
	    }
	    return newObj;
	}
	function gxtoken(){
		var time=0;
		if(self.data().time){
			time=(Date.parse(new Date())/1000)-(self.data().time);
		}else{
			layui.data('nepadmin',{
				key:'time',
				value:Date.parse(new Date())/1000
			});
		}
		if(time>7200){
			self.logout();
		}
		setInterval(function(){
			time++;
			if(time>3600&&time<7200){

				time=0;
				layui.data('nepadmin',{
					key:'time',
					value: Date.parse(new Date())/1000
				});
				self.ajax('admins/extended',{},1).then(function(res){});
			}
		},1000);
	}
	if(self.data().user){
		gxtoken();
	}
	//时间戳转换
	Date.prototype.format = function (fmt) { //author: meizz  
    	    var o = {  
    	        "M+": this.getMonth() + 1, //月份  
    	        "d+": this.getDate(), //日  
    	        "h+": this.getHours(), //小时  
    	        "m+": this.getMinutes(), //分  
    	        "s+": this.getSeconds(), //秒   
    	        "q+": Math.floor((this.getMonth() + 3) / 3),    //q是季度
    	        "S": this.getMilliseconds() //毫秒  
    	    };  
    	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
    	    for (var k in o)  
    	        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
    	    return fmt;  
    	}  
    	  
    	String.prototype.format = function (args) {  
    	    var result = this;  
    	    if (arguments.length > 0) {  
    	        if (arguments.length == 1 && typeof (args) == "loginTime") {  
    	            for (var key in args) {  
    	                if (args[key] != undefined) {  
    	                    var reg = new RegExp("({" + key + "})", "g");  
    	                    result = result.replace(reg, args[key]);  
    	                }  
    	            }  
    	        }  
    	        else {  
    	            for (var i = 0; i < arguments.length; i++) {  
    	                if (arguments[i] != undefined) {  
    	                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题  
    	                    var reg = new RegExp("({)" + i + "(})", "g");  
    	                    result = result.replace(reg, arguments[i]);  
    	                }  
    	            }  
    	        }  
    	    }  
    	    return result;  
    	}
	self.dateFormat=function(value){
		return value ? new Date(value*1000).format("yyyy-MM-dd hh:mm:ss") : "";  
	}
    self.login = function(token, data, isSession) {
		gxtoken();
      self.data(
        {
          key: conf.tokenName,
          value: token
        },
        isSession && sessionStorage
      )
      if ($.isPlainObject(data)) {
        var disableData = []
        layui.each(data, function(key) {
          disableData.push({
            key: key,
            value: data[key]
          })
        })
        self.data(disableData)
      }
    }
    //初始化整个页面
    self.initPage = function(initCallback) {
      //加载样式文件
      layui.each(layui.conf.style, function(index, url) {
        layui.link(url + '?v=' + conf.v)
      })
	  
      self.initView(self.route)
    }
    self.post = function(params) {
      view.request($.extend({ type: 'post' }, params))
    }

    /**
    self.router = function(url) {
      var route
      if (url) {
        url = '#' + url
        if (url == '#/') url += conf.entry
        console.log(url)
      } else {
        route = layui.router()
      }
      route.fileurl = '/' + route.path.join('/')
      return route
    }
     */
    //初始化视图区域
    self.initView = function(route) {
		if(route.href){
			view.flag=true;
		}
      if (!self.route.href || self.route.href == '/') {
        self.route = layui.router('#' + conf.entry)
        route = self.route
      }
      route.fileurl = '/' + route.path.join('/')
      //判断登录页面
      if (conf.loginCheck == true) {
        if (self.getLoginToken()) {
          if (route.fileurl == conf.loginPage) {
            self.navigate('/')
            return
          }
        } else {
          if (route.fileurl != conf.loginPage) {
            self.logout()
            return
          }
        }
      }
	  /* if(self.data().user){
		  if(location.href.indexOf('index.html')==-1&&self.data().user.type==1){
				  alert('请先退出管理员登录，再进入代理商后台');
		  		  location.href='index.html';
		  }else if(location.href.indexOf('index.html')!=-1&&self.data().user.type==2){
				  alert('请先退出代理商登录，再进入管理员后台');
		  		  location.href='agentIndex.html';
		  }
	  } */
	  
      if ($.inArray(route.fileurl, conf.indPage) === -1/* &&(location.href.indexOf('index.html')==-1&&self.data().agentUser||location.href.indexOf('index.html')!=-1&&self.data().user) */) {
        
		var loadRenderPage = function(params) {
          if (conf.viewTabs == true) {
			
			
            view.renderTabs(route)
          } else {
            view.render(route.fileurl)
          }
        }

        if (view.containerBody == null) {
          //加载layout文件
          view.renderLayout(function() {
            //重新渲染导航
            element.render('nav', 'nepadmin-sidebar')
            //加载视图文件
            loadRenderPage()
          })
        } else {
          //layout文件已加载，加载视图文件
          loadRenderPage()
        }
      } else {
		  /* if(location.href.indexOf('index.html')==-1){
			  route.fileurl='/user/agentLogin';
		  }else{
			  route.fileurl='/user/login';
		  } */
        //加载单页面
        view.renderIndPage(route.fileurl, function() {
          if (conf.viewTabs == true) view.tab.clear()
        })
      }
    }
    //根据当前加载的URL高亮左侧导航
    self.sidebarFocus = function(url) {
      url = url || self.route.href
      var elem = $('#app-sidebar')
        .find('[lay-href="' + url + '"]')
        .eq(0)
      if (elem.length > 0) {
        elem.parents('.layui-nav-item').addClass('layui-nav-itemed')
        elem.click()
      }
    }
    self.flexible = function(open) {
      if (open == true) {
        view.container.removeClass(self.shrinkCls)
      } else {
        view.container.addClass(self.shrinkCls)
      }
    }
    self.on = function(name, callback) {
      return layui.onevent(conf.eventName, 'system(' + name + ')', callback)
    }
    self.event = function(name, params) {
      layui.event(conf.eventName, 'system(' + name + ')', params)
    }
    self.csshref = function(name) {
      name = name == undefined ? self.route.path.join('/') : name
      return conf.css + 'views/' + name + '.css' + '?v=' + conf.v
    }
    self.prev = function(n) {
      if (n == undefined) n = -1
      window.history.go(n)
    }
    
    

    self.modal = {}
    self.modal.info = function(msg, params) {
      params = params || {}
      params.titleIcoColor = params.titleIcoColor || '#5a8bff'
      params.titleIco = params.titleIco || 'exclaimination'
      params.title = [
        '<i class="layui-icon layui-icon-' +
          params.titleIco +
          '" style="font-size:12px;background:' +
          params.titleIcoColor +
          ';display:inline-block;position:relative;top:-2px;height:24px;line-height:24px;text-align:center;width:24px;color:#fff;border-radius:50%;margin-right:10px;"></i>' +
          (params.title || '提醒'),
        'background:#fff;border:none;font-weight:bold;font-size:18px;color:#08132b;padding-top:20px;height:46px;line-height:46px;padding-bottom:0;'
      ]
      params = $.extend(
        {
          btn: ['我知道了'],
          skin: 'layui-layer-admin-modal',
          area: [windowWidth <= 750 ? '90%' : '50%'],
          closeBtn: 0,
          shadeClose: true
        },
        params
      )
      layer.alert(msg, params)
    }
    self.modal.success = function(msg, params) {
      params = params || {}
      params.titleIco = 'ok'
      params.titleIcoColor = '#30d180'
      self.modal.info(msg, params)
    }
    self.modal.warn = function(msg, params) {
      params = params || {}
      params.titleIco = 'exclaimination'
      params.titleIcoColor = '#ff9900'
      self.modal.info(msg, params)
    }
    self.modal.error = function(msg, params) {
      params = params || {}
      params.titleIco = 'close'
      params.titleIcoColor = '#ed4014'
      self.modal.info(msg, params)
    }
    self.isUrl = function(str) {
      return /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/.test(
        str
      )
    }
    self.popup = function(params) {
      var url = params.url || ''
      var success = params.success || function() {}
      params.skin = 'layui-layer-admin-page'
      POPUP_DATA = params.data || {}
      var defaultParams = {
        type: 1,
        area: ['90%', '90%'], //宽高
        shadeClose: true
      }
      if (self.isUrl(url)) {
        params.type = 2
        params.content = url
        layer.open($.extend(defaultParams, params))
        return
      }
	  
      view.tab.del(url)

      view.loadHtml(conf.views + url, function(res) {
        var htmlElem = $('<div>' + res.html + '</div>')

        if (params.title === undefined) {
          params.title = htmlElem.find('title').text() || '信息'
          if (params.title) htmlElem.find('title').remove()
        }

        params.content = htmlElem.html()
        params.success = function(layer, index) {
          success(layer, index)

          view.parse(layer)
          //重新对面包屑进行渲染
          element.render('breadcrumb', 'nepadmin-breadcrumb')
        }

        params = $.extend(defaultParams, params)
        layer.open($.extend(defaultParams, params))
      })
    }

    //当小于这个尺寸的时候会进行手机端的适配
    var mobileWidth = 991
    var isMobileAdapter = false
    function mobileAdapter() {
      self.flexible(false)
      var device = layui.device()
      if (device.weixin || device.android || device.ios) {
        //点击空白处关闭侧边栏
        $(document).on('click', '#' + conf.containerBody, function() {
          if (
            $(window).width() < mobileWidth &&
            !view.container.hasClass(self.shrinkCls)
          ) {
            self.flexible(false)
          }
        })
      }
      isMobileAdapter = true
    }
    $(window).on('resize', function(e) {
      if ($(window).width() < mobileWidth) {
        if (isMobileAdapter == true) return
        mobileAdapter()
      } else {
        isMobileAdapter = false
      }
    })

    $(window).on('hashchange', function(e) {
      //移动端跳转链接先把导航关闭
      if ($(window).width() < mobileWidth) {
        self.flexible(false)
      }
      self.route = layui.router()
      layer.closeAll()
      self.initView(self.route)
    })

    //回车提交 form 表单
    $(document).on('keydown', function(e) {
      var ev = document.all ? window.event : e
      if (ev.keyCode == 13) {
        var form = $(':focus').parents('.layui-form')
        form.find('[lay-submit]').click()
      }
    })

    $(document).on('click', '[lay-href]', function(e) {
      var href = $(this).attr('lay-href')
      var target = $(this).attr('target')
      if (href == '') return
      if (self.isUrl(href)) {
        next()
      }
	  if(href!=$('.nepadmin-tabs-item').attr('lay-url')&&href!='/'){
		$('.nepadmin-tabs-item').remove();
	  }
	  view.flag=true;
      function next() {
        target == '__blank' ? window.open(href) : self.navigate(href)
	  }
      if ($.isFunction(self.routeLeaveFunc)) {
        self.routeLeaveFunc(self.route, href, next)
      } else {
        next()
      }

      return false
    })
    $(document).on('click', '[lay-popup]', function(e) {
      var params = $(this).attr('lay-popup')
      self.popup(
        params.indexOf('{') === 0
          ? new Function('return ' + $(this).attr('lay-popup'))()
          : { url: params }
      )
      return false
    })
    $(document).on('mouseenter', '[lay-tips]', function(e) {
      var title = $(this).attr('lay-tips')
      var dire = $(this).attr('lay-dire') || 3
      if (title) {
        layer.tips(title, $(this), {
          tips: [dire, '#263147']
        })
      }
    })
    $(document).on('mouseleave', '[lay-tips]', function(e) {
      layer.closeAll('tips')
    })

    $(document).on('click', '*[' + conf.eventName + ']', function(e) {
      self.event($(this).attr(conf.eventName), $(this))
    })

    var shrinkSidebarBtn =
      '.' + self.shrinkCls + ' #app-sidebar .layui-nav-item a'

    $(document).on('click', shrinkSidebarBtn, function(e) {
      if (isMobileAdapter == true) return
      var chileLength = $(this)
        .parent()
        .find('.layui-nav-child').length
      if (chileLength > 0) {
        self.flexible(true)
        layer.closeAll('tips')
      }
    })
    $(document).on('mouseenter', shrinkSidebarBtn, function(e) {
      var title = $(this).attr('title')
      if (title) {
        layer.tips(title, $(this).find('.layui-icon'), {
          tips: [2, '#263147']
        })
      }
    })
    $(document).on('mouseleave', shrinkSidebarBtn, function(e) {
      layer.closeAll('tips')
    })
	$(document).click(function(){
		$('.layui-form-select').removeClass('layui-form-selected');
	});
	$(document).on('click','.layui-form-select dd',function(){
		if($(this).attr('data')||$(this).attr('data')===0){
			$(this).parent().siblings().find('input').val($(this).html()).attr('data',$(this).attr('data'));
		}else{
			$(this).parent().siblings().find('input').val('').attr('data','');
		}
		$(this).addClass('layui-this').siblings().removeClass('layui-this');
	});
	$(document).on('click','.layui-form-select',function(e){
		if($(this).hasClass('layui-form-selected')){
			$(this).removeClass('layui-form-selected');
		}else{
			$('.layui-form-select').removeClass('layui-form-selected');
			$(this).addClass('layui-form-selected');
		}
		e.stopPropagation();
	});

    self.on('flexible', function(init) {
      var status = view.container.hasClass(self.shrinkCls)
      self.flexible(status)
      self.data({ key: 'flexible', value: status })
    })
    self.on('refresh', function(e) {
      var url = self.route.href
      if (conf.viewTabs == true) {
        view.tab.refresh(url);
      } else {
        view.render(location.hash)
      }
    })
    self.on('prev', function(e) {
      self.prev()
    })

    self.on('logout', function(e) {
		layer.confirm('确定要退出登录吗？', function(index) {
			self.ajax('login/login_out').then(function(res){
				setTimeout(function(){
					self.logout();
				},500)
			}).catch(function(res){});
		});
    })
	  self.on('update_paswd', function(e) {
		  var formurl='auser/update_pwd',formarea=['400px', '330px'];
		  layui.admin.pupF('修改密码',formarea,formurl, 1, '');
		  return false;
		  // layer.confirm('确定要退出登录吗？', function(index) {
			//   self.ajax('login/login_out').then(function(res){
			// 	  setTimeout(function(){
			// 		  self.logout();
			// 	  },500)
			//   }).catch(function(res){});
		  // });
	  })
    self.on('fullscreen', function(e) {
      var normalCls = 'layui-icon-screen-full'
      var activeCls = 'layui-icon-screen-restore'
      var ico = e.find('.layui-icon')

      if (ico.hasClass(normalCls)) {
        var e = document.body
        e.webkitRequestFullScreen
          ? e.webkitRequestFullScreen()
          : e.mozRequestFullScreen
          ? e.mozRequestFullScreen()
          : e.requestFullScreen && e.requestFullscreen()
        ico.removeClass(normalCls).addClass(activeCls)
      } else {
        var e = document
        e.webkitCancelFullScreen
          ? e.webkitCancelFullScreen()
          : e.mozCancelFullScreen
          ? e.mozCancelFullScreen()
          : e.cancelFullScreen
          ? e.cancelFullScreen()
          : e.exitFullscreen && e.exitFullscreen()
        ico.removeClass(activeCls).addClass(normalCls)
      }
    })

    if ($(window).width() <= mobileWidth) {
      mobileAdapter()
    } else {
      var flexibleOpen = self.data().flexible
      self.flexible(flexibleOpen === undefined ? true : flexibleOpen)
    }

    exports('admin', self)
  })
